package http

import (
	"fmt"
	"log"
	"net"
	"time"
)

// ========================================
// HTTP协议转发器实现
// 实现 core.QUICForwarder 的HTTP部分
// ========================================

// Forwarder HTTP协议转发器
type Forwarder struct {
	quicServer QUICServerInterface
}

// QUICServerInterface QUIC服务器接口（避免循环依赖）
type QUICServerInterface interface {
	SendRequestToClient(tunnelID, requestID string, httpReq []byte, responseWriter net.Conn) error
}

// NewForwarder 创建HTTP转发器
func NewForwarder(quicServer QUICServerInterface) *Forwarder {
	return &Forwarder{
		quicServer: quicServer,
	}
}

// ForwardHTTPRequest 转发HTTP请求（旧方法，保留兼容性）
func (f *Forwarder) ForwardHTTPRequest(tunnelID, requestID string, httpReq []byte) ([]byte, error) {
	log.Printf("🌐 [HTTP转发器] 转发请求: TunnelID=%s, RequestID=%s, Size=%d bytes",
		tunnelID[:8]+"...", requestID[:8]+"...", len(httpReq))

	// 创建一个管道用于接收响应
	respChan := make(chan []byte, 1)
	errChan := make(chan error, 1)

	// 包装为net.Conn接口
	pr, pw := net.Pipe()
	defer pr.Close()
	defer pw.Close()

	// 异步读取响应
	go func() {
		buf := make([]byte, 1024*1024) // 1MB buffer
		n, err := pr.Read(buf)
		if err != nil {
			errChan <- err
			return
		}
		respChan <- buf[:n]
	}()

	// 调用QUIC服务器的SendRequestToClient方法
	if err := f.quicServer.SendRequestToClient(tunnelID, requestID, httpReq, pw); err != nil {
		return nil, fmt.Errorf("发送请求失败: %w", err)
	}

	// 等待响应
	select {
	case resp := <-respChan:
		log.Printf("✅ [HTTP转发器] 收到响应: Size=%d bytes", len(resp))
		return resp, nil
	case err := <-errChan:
		return nil, fmt.Errorf("读取响应失败: %w", err)
	case <-time.After(30 * time.Second):
		return nil, fmt.Errorf("响应超时")
	}
}

// ForwardHTTPRequestStream 流式转发HTTP请求（支持大文件，实现core.QUICForwarder接口）
func (f *Forwarder) ForwardHTTPRequestStream(tunnelID, requestID string, httpReq []byte, responseWriter net.Conn) error {
	log.Printf("🌐 [HTTP转发器] 流式转发请求: TunnelID=%s, RequestID=%s, Size=%d bytes",
		tunnelID[:8]+"...", requestID[:8]+"...", len(httpReq))

	// 直接调用QUIC服务器的SendRequestToClient方法
	// 响应会被流式写入responseWriter
	if err := f.quicServer.SendRequestToClient(tunnelID, requestID, httpReq, responseWriter); err != nil {
		return fmt.Errorf("流式转发失败: %w", err)
	}

	return nil
}

// ForwardTCPConnection TCP转发（HTTP协议不实现）
func (f *Forwarder) ForwardTCPConnection(tunnelID, requestID string, clientConn net.Conn) error {
	return fmt.Errorf("HTTP转发器不支持TCP连接转发")
}
